/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.google.cse.emea.universaltransformer.editors;

import com.google.cse.emea.jct.utils.Profile;
import java.util.HashMap;
import java.util.ServiceLoader;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author jtrapp
 */
public class EditorFactory {

    private static ServiceLoader<EditorInterface> editorLoader =
            ServiceLoader.load(EditorInterface.class);
    private HashMap<String, String> editors;
    private HashMap<String, EditorInterface> editorCache;
    private static EditorFactory instance = null;

    /**
     * The Factory
     */
    public static EditorFactory getFactory() {
        
        if (instance == null) {
            instance = new EditorFactory();
        }
        return instance;
    }

    private EditorFactory() {
        editorCache = new HashMap<String, EditorInterface>();
        editors = new HashMap<String, String>();
        
        /** Add all inputPanels to the card panel.*/
        for (EditorInterface editor : editorLoader) {
            String[] types = editor.getTypes();
            for (String type : types) {
                editorCache.put(type, editor);
            }
        }
    }

    /**
     * Get an Editor for a mime type
     * @param type Mime Type
     * @return The editor, that is able to display that type.
     */
    public static EditorInterface getEditor(String type) {
        getFactory();

        return instance.editorCache.get(type);
    }

    public EditorInterface getEditor(Profile profile, String key, String type) {
        try {
            if (editors == null) {
                editors = profile.loadTable(key);
            }
            String classname = editors.get(type);

            EditorInterface editor = editorCache.get(classname);
            if (editor == null) {
                editor = (EditorInterface) Class.forName(classname).newInstance();
                editorCache.put(classname, editor);
            }

            return editor;
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(EditorFactory.class.getName()).log(Level.SEVERE, "Could not find editor for " + type, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(EditorFactory.class.getName()).log(Level.SEVERE, "Can't instantiate editor for " + type, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(EditorFactory.class.getName()).log(Level.SEVERE, "Illegal access for editor for " + type, ex);
        }
        return null;
    }
}
